<template>
    <div>
        <el-row class="tac">
            <el-col :span="4" >
                <div style="width: 100%;height: 100px;position: relative;" @click="curIndex = '' ">
                    <span></span>
                </div>
            </el-col>
            <el-col :span="16" >
                <el-container>
                    <el-header>
                        <div class="filter-container" @click="curIndex = '' ">
                            <h3 style="display: inline-block;margin-right: 10px">{{mtitle}}</h3>
                            <span style="display: inline-block;margin-left: 10px;margin-right: 15px">
                            共计{{questions.length}}道(含章节目录类)
                            </span>

                            <el-input
                                    style="width: 400px;"
                                    v-model="uid"

                            >
                                <template slot="prepend">当前用户为:</template>
                            </el-input>

                            <el-button
                                    type="success"
                                    @click="upDataAnswer"
                                    v-if="!isLook"
                            >
                                答题完成
                            </el-button>

                        </div>
                    </el-header>
                    <el-main>
                        <div  class="qu-content">
                            <section class="qu-item"
                                     v-for="(item, index) in questions"
                                     :key="item.realSort"
                                     @click="curIndex = index; "
                            >
                                <answer_chained :id="item.type+item.realSort"
                                              v-if="item.type === 'chained'" :itemIndex="index"
                                                :isSlectThis="curIndex === index"
                                              :itemData="item"
                                              :itemUpDataAnswer = "upDataItemAnswer"
                                                :isLook="isLook"
                                ></answer_chained>
                                <answer_checkbox :id="item.type+item.realSort" v-if="item.type === 'checkbox'" :itemIndex="index"
                                                 :isSlectThis="curIndex === index"
                                                :itemData="item"
                                                :itemUpDataAnswer = "upDataItemAnswer"
                                                 :isLook="isLook"
                                ></answer_checkbox>
                                <answer_head v-if="item.type === 'head'"
                                                :itemData="item"
                                ></answer_head>
                                <answer_radio :id="item.type+item.realSort" v-if="item.type === 'radio'" :itemIndex="index"
                                              :isSlectThis="curIndex === index"
                                                :itemData="item"
                                                :itemUpDataAnswer = "upDataItemAnswer"
                                              :isLook="isLook"
                                ></answer_radio>
                                <answer_textarea :id="item.type+item.realSort" v-if="item.type === 'textarea'" :itemIndex="index"
                                                 :isSlectThis="curIndex === index"
                                              :itemData="item"
                                              :itemUpDataAnswer = "upDataItemAnswer"
                                                 :isLook="isLook"
                                ></answer_textarea>
                            </section>
                        </div>

                    </el-main>
                </el-container>
            </el-col>
            <el-col :span="4" >
                <p></p>
                <div class="fixed-header-right" @click="curIndex = '' ">
                    <h5 class="left-sidebar-title">章节目录</h5>
                    <el-menu
                            class="el-menu-vertical-demo"
                            @select="gotoTitle"
                            background-color="#819CD9"
                            text-color="#fff"
                            active-text-color="#ffd04b">
                        <el-menu-item :index="item.type+item.realSort" v-for="(item, index) in title_list">
                            <svg-icon icon-class="跳转" style="margin-right:5px"/>
                            <span slot="title">{{item.viewSort+"/"+item.title}}</span>
                        </el-menu-item>

                    </el-menu>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import  {new_answer}  from '@/utils/newQuestion'
    import answer_chained from './components/answer_chained'
    import answer_checkbox from './components/answer_checkbox'
    import answer_head from './components/answer_head'
    import answer_radio from './components/answer_radio'
    import answer_textarea from './components/answer_textarea'
    import { postBody,post} from "@/utils/httpUtil";
    export default {
        name: "doAnswer",
        components: {
            answer_chained,
            answer_checkbox,
            answer_head,
            answer_radio,
            answer_textarea,
        },
        data() {
            return {
                mid:null,
                mtitle:'新建问卷',
                questions:[],
                new_answer:new_answer,
                curIndex:'',
                uid:'',
                isLook:false,

            }
        },
        computed: {
            // 计算属性的 getter
            answerCount: function () {
                // `this` 指向 vm 实例
                return Number(this.questions.length)
            },
            title_list(){
                if(this.questions.length>0){
                    return this.questions.filter((q,index,self)=>{
                        return q.type === 'head';
                    })
                }
                return [];
            },
        },
        methods: {
            getQetionesList() {
                let remap ={};
                remap.mid = this.mid;
                if(this.uid){
                    remap.uid =  this.uid
                }
                postBody("/questionItem/getByMIdUid", remap).then(resp => {
                    if(resp.result) {
                        let tem_questions = resp.data;
                        tem_questions.forEach((item, index) => {
                            if(item.type !== 'head'){
                                if(!item.answer){
                                    let newAn = JSON.parse(JSON.stringify(this.new_answer));
                                    newAn.mouldId = this.mid;
                                    newAn.itemId = item.id;
                                    newAn.isSelect = item.isSelect;
                                    newAn.isChildAnswer = item.isChildAnswer;
                                    newAn.isOther = item.isOther;
                                    item.answer = newAn
                                }else{
                                    //checkbox和chained数组化
                                    if(item.answer.options.length>36){
                                        item.answer.options =item.answer.options.split(",");
                                    }
                                }
                            }
                        });
                        this.questions = tem_questions
                    } else {
                        this.$notify({
                            title: '提示',
                            message: '题目失败！'+resp.msg,
                            type: 'warning',
                            duration: 2000
                        })
                    }
                })
            },
            upDataAnswer(){
                this.curIndex = '';
                if(!this.uid){
                    this.$confirm('是否匿名回答问卷?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let localIp =  require('ip');
                        this.uid = "匿名|"+localIp.address();
                        let answer_list = this.checkRules();
                        if(answer_list && answer_list.length>0){
                            //最新的自定义的用户
                            answer_list.forEach((item, index) => {
                                item.uid = this.uid
                            });
                            //保存至后台
                            let url = "/quUserQues/addOrUpdate";
                            postBody(url, answer_list).then(resp => {
                                if(resp.result) {
                                    this.$notify({
                                        title: '提示',
                                        message: '问题回答成功！',
                                        type: 'success',
                                        duration: 2000
                                    })
                                    this.$router.push({path: '/home/viewQue', query: {}})
                                } else {
                                    this.$notify({
                                        title: '提示',
                                        message: '问题回答失败！'+resp.msg,
                                        type: 'warning',
                                        duration: 2000
                                    })
                                }
                            })
                        }else{
                            return
                        }
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '请输入用户名'
                        });
                    })
                }else{
                    let answer_list = this.checkRules();
                    if(answer_list && answer_list.length>0){
                        //最新的自定义的用户
                        answer_list.forEach((item, index) => {
                            item.uid = this.uid
                        });
                        //保存至后台
                        let url = "/quUserQues/addOrUpdate";
                        postBody(url, answer_list).then(resp => {
                            if(resp.result) {
                                this.$notify({
                                    title: '提示',
                                    message: '问题回答成功！',
                                    type: 'success',
                                    duration: 2000
                                })
                                this.$router.push({path: '/home/viewQue', query: {}})
                            } else {
                                this.$notify({
                                    title: '提示',
                                    message: '问题回答失败！'+resp.msg,
                                    type: 'warning',
                                    duration: 2000
                                })
                            }
                        })
                    }else{
                        return
                    }
                }

            },
            upDataItemAnswer(index,item){
                this.$set(this.questions,index,item)
            },
            checkRules(){
                let answer_list = [];
                let questions_list = JSON.parse(JSON.stringify(this.questions));
                try {
                    questions_list.forEach((item, index) => {
                        let item_errMsg = '';
                        if(item.type === 'radio'){
                            item_errMsg = this.checkRequired(item,item_errMsg);
                        }else if(item.type === 'checkbox'){
                            item_errMsg = this.checkRequired(item,item_errMsg);
                            item_errMsg = this.checkSelectNum(item,item_errMsg);
                        }else if(item.type === 'chained'){
                            item_errMsg = this.checkRequired(item,item_errMsg);
                            item_errMsg = this.checkSelectNum(item,item_errMsg);
                        }else if(item.type === 'textarea'){
                            item_errMsg = this.checkRequired(item,item_errMsg);
                        }
                        if(item_errMsg){
                            this.gotoQues(item,item_errMsg);
                            throw Error();
                        }else{
                            if(item.type !== 'head'){
                                item.answer.options = item.answer.options.toString();
                                answer_list.push(item.answer)
                            }
                        }
                    });
                } catch(e){
                    return null;

                }
                return answer_list;

            },
            checkRequired(que_item,errMsg){
                if(que_item.required === 1){
                    if(que_item.type === 'radio'){
                        if(que_item.answer.options.length<1){
                            errMsg = que_item.errorMsg
                        }
                    }else if(que_item.type === 'checkbox'){
                        if(que_item.answer.options.length<1){
                            if(!que_item.answer.otherValue){
                                errMsg = que_item.errorMsg
                            }
                        }
                    }else if(que_item.type === 'chained'){
                        if(que_item.answer.options.length<1){
                            if(!que_item.answer.otherValue){
                                errMsg = que_item.errorMsg
                            }
                        }
                    }else if(que_item.type === 'textarea'){
                        if(!que_item.answer.textValue){
                            errMsg = que_item.errorMsg
                        }
                    }
                }
                return errMsg;
            },
            checkSelectNum(que_item,errMsg){
                let tipText ="";
                let tipNum = 0;
                if(que_item.selectNum === 0){

                }else if(que_item.selectNum >0){
                    tipNum = que_item.selectNum;
                    tipText = "/最多选"+tipNum+"个!"
                }else{
                    tipNum = -que_item.selectNum;
                    tipText = "/最少选"+tipNum+"个!"
                }
                let selected_Num =0;
                if(que_item.answer.options.length>0){
                    if(typeof que_item.answer.options === 'string'){
                        selected_Num=1
                    }else{
                        selected_Num = que_item.answer.options.length
                    }
                }

                if(que_item.answer.otherValue){
                    selected_Num = selected_Num+1
                }

                if(que_item.selectNum === 0){
                }else if(que_item.selectNum >0){
                    if(selected_Num>tipNum){
                        errMsg = errMsg+ tipText
                    }
                }else{
                    if(selected_Num<tipNum){
                        errMsg = errMsg+ tipText
                    }
                }
                return errMsg;
            },

            gotoQues(item,errMsg){
                let hash = item.type+item.realSort+'';
                document.getElementById(hash).classList.add("waring_border");
                document.getElementById(hash).scrollIntoView({block:"center"});
                this.$alert(errMsg, '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                        document.getElementById(hash).classList.remove("waring_border");
                        document.getElementById(hash).scrollIntoView({block:"center"});
                    }
                });
            },
            gotoTitle(hash,path){
                document.getElementById(hash).scrollIntoView(true);
            },
            addPageviews(){
                post("/questionMould/addPageviews", {id:this.mid}).then(resp => {
                    if(resp.result) {
                    } else {
                        this.$notify({
                            title: '提示',
                            message: '新增浏览数失败！'+resp.msg,
                            type: 'warning',
                            duration: 2000
                        })
                    }
                })
            },
            getLocalIP() {
                var os = require('os');
                var map = [];
                var ifaces = os.networkInterfaces();
                console.log(ifaces)
                for (var dev in ifaces) {
                    if (dev.indexOf('eth0') != -1) {
                        var tokens = dev.split(':');
                        var dev2 = null;
                        if (tokens.length == 2) {
                            dev2 = 'eth1:' + tokens[1];
                        } else if (tokens.length == 1) {
                            dev2 = 'eth1';
                        }
                        if (null == ifaces[dev2]) {
                            continue;
                        }

                        // 找到eth0和eth1分别的ip
                        var ip = null, ip2 = null;
                        ifaces[dev].forEach(function(details) {
                            if (details.family == 'IPv4') {
                                ip = details.address;
                            }
                        });
                        ifaces[dev2].forEach(function(details) {
                            if (details.family == 'IPv4') {
                                ip2 = details.address;
                            }
                        });
                        if (null == ip || null == ip2) {
                            continue;
                        }

                        // 将记录添加到map中去
                        if (ip.indexOf('10.') == 0 ||
                            ip.indexOf('172.') == 0 ||
                            ip.indexOf('192.') == 0) {
                            map.push({"intranet_ip" : ip, "internet_ip" : ip2});
                        } else {
                            map.push({"intranet_ip" : ip2, "internet_ip" : ip});
                        }
                    }
                }
                return map;
            },
        },
        created() {
            // let q_mid = this.$route.params.mid
            // let mtitle = this.$route.params.mtitle
            // let uid = this.$route.params.uid
            // let isLook = this.$route.params.isLook
            let q_mid = this.$route.query.mid
            let mtitle = this.$route.query.mtitle
            let uid = this.$route.query.uid
            let isLook = this.$route.query.isLook
            if(q_mid){
                this.mid = q_mid
                this.mtitle = mtitle
            }
            if(uid){
                this.uid =uid
            }
            if(isLook){
                if(isLook === 'true'){
                    this.isLook = true
                }else{
                    this.isLook = false
                }
            }
            if(this.mid){
                this.getQetionesList()
                this.addPageviews()
            }
        }
    }
</script>

<style scoped lang="scss">
    .fixed-header-right {
        margin-top: 3%;
        width: 9%;
        height: 100vh;
        position: fixed;
        top: 0;
        right: 0;
        z-index: 40000;
    }
    .left-sidebar-title{
        position: relative;
        width: 100%;
        height: 50px;
        line-height: 50px;
        background: #407ee6;
        text-align: center;
        overflow: hidden;
        display: inline-block;
        margin: 0;
        color: #fff;
        font-weight: 600;
        line-height: 50px;
        font-size: 14px;
        font-family: Avenir, Helvetica Neue, Arial, Helvetica, sans-serif;
        vertical-align: middle;
    }
    .qu-content {
        padding: 2rem;

        border: {
            top: 2px solid #bbb;
            bottom: 2px solid #bbb;
        }

        .qu-item {
            position: relative;
            margin-bottom: 1rem ;
            border-bottom:2px solid #6ca9e7;
            }
    }
    .waring_border{
        border: 2px solid red

    }
</style>
